package com.ycode.bang.anbang.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.R;
import com.ycode.bang.anbang.adapter.SelectTimeAdapter;
import com.ycode.bang.anbang.adapter.SelectTroubleAdapter;
import com.ycode.bang.anbang.baseui.BaseActivity;
import com.ycode.bang.anbang.customview.MyGridView;
import com.ycode.bang.anbang.merchantactivity.LocalImageActivity;
import com.ycode.bang.anbang.model.PersonTrouble;
import com.ycode.bang.anbang.model.PersonTrouble2;
import com.ycode.bang.anbang.model.PersonTrouble3;
import com.ycode.bang.anbang.model.PersonTrouble4;
import com.ycode.bang.anbang.model.SelectPeopleModel;
import com.ycode.bang.anbang.model.SelectTrouble;
import com.ycode.bang.anbang.network.FinalHttpService;
import com.ycode.bang.anbang.network.FinalHttpUtil;
import com.ycode.bang.anbang.network.servicelistener.WithJsonListener;
import com.ycode.bang.anbang.utils.CommonViewHolder;
import com.ycode.bang.anbang.utils.DialogProgress;
import com.ycode.bang.anbang.utils.DialogWithDelete;
import com.ycode.bang.anbang.utils.RequestMapDev;
import com.ycode.bang.anbang.utils.SaveImage;
import com.ycode.bang.anbang.utils.SetImage;
import com.ycode.bang.anbang.utils.TAkePhotos;
import com.ycode.bang.anbang.utils.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 创建公共工单
 */

public class CreatePersonActivity extends BaseActivity implements View.OnClickListener {
    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.recommendGridView)
    MyGridView recommendGridView;
    @InjectView(R.id.tv_plot)
    TextView mTvPlot;//
    @InjectView(R.id.tv_name)
    TextView mTvName;//
    @InjectView(R.id.tv_number)
    TextView mTvNumber;//
    @InjectView(R.id.btn_address)
    Button mBtnAddress;//编辑地址
    //    @InjectView(R.id.tv_select_leixing)
//    TextView mTvSelect;//选择类型
    @InjectView(R.id.edit_contect)
    EditText mEvContect;//报修类型

    @InjectView(R.id.yiban)
    RadioButton yiban;//级别一般
    @InjectView(R.id.zhonyao)
    RadioButton zhonyao;//级别重要
    @InjectView(R.id.btn_complete)
    Button mBtnCl;//确认创建
    @InjectView(R.id.lin_xieyi)
    LinearLayout lin_xieyi;//查看那个收费标准

    @InjectView(R.id.tv_select_fwsj)
    TextView mTvSelectFwsj;//服务时间


    @InjectView(R.id.frist_GridView)
    MyGridView fristGridView;
    @InjectView(R.id.second_GridView)
    MyGridView secondGridView;
    @InjectView(R.id.third_GridView)
    MyGridView thirdGridView;
    private SelectTroubleAdapter firstAdapter;
    private SelectTroubleAdapter secondAdapter;
    private SelectTroubleAdapter thirdAdapter;
    private ArrayList<SelectTrouble> firstList = new ArrayList<SelectTrouble>();
    private ArrayList<SelectTrouble> secondList = new ArrayList<SelectTrouble>();
    private ArrayList<SelectTrouble> thirdList = new ArrayList<SelectTrouble>();

    public static final int INFORMATION = 20169;
    private Uri sCurrentUri;//拍照时用于存放图片Uri
    private Dialog dialog;
    private ImagesAdapter imagesAdapter;
    private static final String FRIEND_CIRCLE_ADD_PICTURE = "friend_circle_and_picture";
    public static final int REQUEST_PICTURE_CODE = 20163;
    public static final int PHOTO_REQUEST_CAMERA = 20164;// 拍照
    private int imagelistsize = 0;//图片列表长度
    private ArrayList<String> sendtoserverimagelist = new ArrayList<String>();
    private ArrayList<String> pathModel = new ArrayList<String>();

    private PersonTrouble troubleList;
    private ArrayList<String> upLoadList = new ArrayList<String>();
    DialogProgress mDialogProgress = new DialogProgress(this);
    private ArrayList<String> idList = new ArrayList<>();
    private String ids = "";
    private String plotid = "";
    private String time = "";//选择的时间段
    private ArrayList<SelectPeopleModel> timeList = new ArrayList<SelectPeopleModel>();//时间
    private ArrayList<SelectPeopleModel> timesList = new ArrayList<SelectPeopleModel>();//时间段
    SelectTimeAdapter adapter2;
    private String flag = "";

    private int firstSelected = 0, secondSelected = 0, thirdSelected = 0;
    private String leixing = "";
    private String leibie = "";
    private String guzhang = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_create_person);
        ButterKnife.inject(this);
        initView();
        initData();
    }

    public void initView() {
        title.setText("个人报修");
        mBtnAddress.setOnClickListener(this);
//        mTvSelect.setOnClickListener(this);
        mBtnCl.setOnClickListener(this);
        lin_xieyi.setOnClickListener(this);
        mTvSelectFwsj.setOnClickListener(this);

        fristGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                firstSelected = position;
                for (int i = 0; i < firstList.size(); i++) {
                    firstList.get(i).setIsCheck(false);
                }
                firstList.get(position).setIsCheck(true);
                leixing = firstList.get(position).getName();
                firstAdapter.notifyDataSetChanged();

                secondList.clear();
                thirdList.clear();
                setSecDate(troubleList.getSubItems().get(position));
                secondAdapter.notifyDataSetChanged();
                thirdAdapter.notifyDataSetChanged();
            }
        });

        secondGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                secondSelected = position;
                for (int i = 0; i < secondList.size(); i++) {
                    secondList.get(i).setIsCheck(false);
                }
                secondList.get(position).setIsCheck(true);
                leibie = secondList.get(position).getName();
                secondAdapter.notifyDataSetChanged();
                thirdList.clear();
                setThirdData(troubleList.getSubItems().get(firstSelected).getSubItems().get(position));
                thirdAdapter.notifyDataSetChanged();
            }
        });

        thirdGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < thirdList.size(); i++) {
                    thirdList.get(i).setIsCheck(false);
                }
                thirdList.get(position).setIsCheck(true);
                guzhang = thirdList.get(position).getName();
                thirdAdapter.notifyDataSetChanged();
            }
        });
    }

    public void initData() {
        getServiceDate();
        getServiceTime();
//        for (int i = 0; i < 4; i++) {
//            if (i == 0) {
//                firstList.add(new SelectTrouble("家电" + i, true));
//            } else {
//                firstList.add(new SelectTrouble("家电" + i, false));
//            }
//        }
        firstAdapter = new SelectTroubleAdapter(this, firstList);
        fristGridView.setAdapter(firstAdapter);

//        for (int i = 0; i < 4; i++) {
//            if (i == 0) {
//                secondList.add(new SelectTrouble("空调" + i, true));
//            } else {
//                secondList.add(new SelectTrouble("空调" + i, false));
//            }
//        }
        secondAdapter = new SelectTroubleAdapter(this, secondList);
        secondGridView.setAdapter(secondAdapter);

//        for (int i = 0; i < 7; i++) {
//            if (i == 0) {
//                thirdList.add(new SelectTrouble("无法开机" + i, true));
//            } else {
//                thirdList.add(new SelectTrouble("无法开机" + i, false));
//            }
//        }
        thirdAdapter = new SelectTroubleAdapter(this, thirdList);
        thirdGridView.setAdapter(thirdAdapter);

        //图片适配器
        if (null != pathModel && null != pathModel) {
            imagelistsize = pathModel.size();
        } else {
            imagelistsize = 0;
        }


        if (pathModel != null && pathModel.size() < 4) {
            pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
        }
        imagesAdapter = new ImagesAdapter(pathModel);
        recommendGridView.setAdapter(imagesAdapter);
    }

    @Override
    protected void getSuccessRequest(Object response, int flag) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_address:
                Intent inforintent = new Intent(this, EditAddress2Activity.class);
                Bundle bundle = new Bundle();
                bundle.putString("plot", "");
                bundle.putString("name", "");
                bundle.putString("number", "");
                bundle.putString("plotid", "");
                inforintent.putExtras(bundle);
                startActivityForResult(inforintent, INFORMATION);
                break;
//            case R.id.tv_select_leixing:
//                select();
//                break;
            case R.id.btn_complete:
                if (TextUtils.isEmpty(mTvName.getText().toString().trim()) || TextUtils.isEmpty(mTvNumber.getText().toString().trim()) || TextUtils.isEmpty(mTvPlot.getText().toString().trim())) {
                    ToastUtil.show(this, "请输入联系信息");
                    return;
                } else if (TextUtils.isEmpty(mEvContect.getText().toString().trim())) {
                    ToastUtil.show(this, "请输入报修内容");
                    return;
                }
//                else if (pathModel.size() == 1 && pathModel.get(0).contains(FRIEND_CIRCLE_ADD_PICTURE)) {
//                    ToastUtil.show(this, "请上传图片");
//                    return;
//                }
                else if (mTvSelectFwsj.getText().toString().trim().equals("请选择服务时间")) {
                    ToastUtil.show(this, "请选择服务时间");
                    return;
                }
                for (String s : pathModel) {
                    if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                        pathModel.remove(s);
                        break;
                    }
                }

                if (pathModel.size() == 0) {
                    createOrder();
                } else {
                    chuli(pathModel);
                }
                break;
            case R.id.lin_xieyi:
//                查看协议
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("plotid", plotid);
                startActivity(intent);
                break;
            case R.id.tv_select_fwsj://选择服务时间
                select2();
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case INFORMATION:
                    Bundle bundle2 = data.getBundleExtra("bundle2");
                    mTvPlot.setVisibility(View.VISIBLE);
                    mTvNumber.setVisibility(View.VISIBLE);
                    mTvPlot.setText(bundle2.getString("plot"));
                    mTvName.setText(bundle2.getString("name"));
                    mTvNumber.setText(bundle2.getString("number"));
                    plotid = bundle2.getString("plotid");
                    getLevel();
                    break;
                //拍照

                case PHOTO_REQUEST_CAMERA:
                    if (hasSdcard()) {
                        Log.e("拍照相片路径", sCurrentUri + "");

                        if (data == null) {
                            String path = sCurrentUri + "";

                            final String cutpath = path.substring(7, path.length());
                            String afterpath = new SaveImage().compressed(cutpath);

                            if (afterpath != null) {
                                Log.e("", afterpath);


                                //先将带“添加符号”的图片删除，然后添加拍照的图片，
                                //最后判断总长度是否为8，若为8，就不操作，否则，添加带“添加符号”的图片

                                for (String s : pathModel) {
                                    if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                                        pathModel.remove(s);
                                        break;
                                    }
                                }
                                pathModel.add("file://" + afterpath);
                                if (pathModel.size() < 4) {
                                    pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
                                }

                                sendtoserverimagelist.add("file://" + afterpath);//用于存放上传服务器的图片列表

                                imagelistsize++;//用于显示的图片列表长度加1

                                imagesAdapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        Toast.makeText(CreatePersonActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }
                    break;

                //选择照片

                case REQUEST_PICTURE_CODE:
                    requestPicture(data);
                    break;
            }
        }
    }

    /**
     * 图片的适配器
     *
     * @param
     * @param
     * @return
     */

    private class ImagesAdapter extends ArrayAdapter<String> {

        private List<String> list;

        public ImagesAdapter(List<String> list) {
            super(CreatePersonActivity.this, 0, list);
            this.list = list;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_item_image_big, null);
            }

            ImageView delete = CommonViewHolder.get(convertView, R.id.delete);
            ImageView imageView = CommonViewHolder.get(convertView, R.id.image_show);
            TextView text = CommonViewHolder.get(convertView, R.id.image_text);
            final String uri = getItem(position);

            //根据是否是“添加图片”显示布局


            if (TextUtils.equals(uri, FRIEND_CIRCLE_ADD_PICTURE)) {
                ImageLoader.getInstance().displayImage("drawable://" + R.mipmap.ic_friend_circle_add_picture, imageView);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                //imageView.setImageResource(R.mipmap.ic_friend_circle_add_picture);
                delete.setVisibility(View.GONE);
                text.setVisibility(View.GONE);
            } else {
                //ImageLoader.getInstance().displayImage(getItem(position), imageView);
                SetImage.setimage(CreatePersonActivity.this, getItem(position), imageView);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                delete.setVisibility(View.VISIBLE);
                text.setVisibility(View.VISIBLE);
            }

            //删除时判断list长度是否小于8，若小于 则直接删除，不用添加“添加符号的图片” ，
            // 否则，先删除选中图片，然后判断原来有没有那张“添加图片”，若有 那就不操作，若无，就添加“添加图片”
            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //删除来自网络图片（编辑状态）

//                    if (netImages != null && netImages.images.size() > 0) {
//                        for (ProductsAndMaterial.Photo s : netImages.images) {
//                            if ((RequestMapDev.BASE_URL.substring(0, RequestMapDev.BASE_URL.length() - 1) + s.url).equals(list.get(position))) {
//                                //FinalHttpWu.deletephoto(ReleaseActivity.this, s.id);
//                                netImages.images.remove(s);
//                                isbianji = true;//此时已经修改过进入界面的信息，（用于退出时判断是否弹dialog）
//                                break;
//                            }
//                        }
//                    }


                    //删除用于上传服务器的图片

                    for (String s : sendtoserverimagelist) {
                        if (s.equals(list.get(position))) {
                            sendtoserverimagelist.remove(s);
                            break;
                        }
                    }


                    if (list.size() < 4) {
                        list.remove(position);

                    } else {
                        list.remove(position);
                        int i = 0;
                        for (String s : list) {
                            if (s.equals(FRIEND_CIRCLE_ADD_PICTURE)) {
                                break;
                            } else {
                                i++;
                                if (i == list.size()) {
                                    list.add(FRIEND_CIRCLE_ADD_PICTURE);
                                }
                            }
                        }
                    }


                    imagelistsize--;//用于显示的列表长度减1

                    imagesAdapter.notifyDataSetChanged();
                }
            });

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TextUtils.equals(uri, FRIEND_CIRCLE_ADD_PICTURE)) {
                        showbgdialog();
                    } else {
                        //查看大图
                    }
                }
            });

            return convertView;
        }
    }

    public void showbgdialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_select_image, null);
        TextView takephoto = (TextView) view.findViewById(R.id.tv_teke_picture);
        TextView select = (TextView) view.findViewById(R.id.tv_select_photo);
        TextView no = (TextView) view.findViewById(R.id.tv_sendContentDialogFragment_cancel);

        final AlertDialog.Builder builder =
                new AlertDialog.Builder(CreatePersonActivity.this, android.R.style.Theme_Holo_Light_Dialog);
        dialog = builder.create();

        dialog.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.mystyle);
        dialog.setCanceledOnTouchOutside(true);

        takephoto.setAlpha(0.85f);
        select.setAlpha(0.85f);
        no.setAlpha(0.85f);

        dialog.show();

//        WindowManager windowManager = context.getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
//        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//        lp.width = (int) (display.getWidth()); //设置宽度
        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) ((dm.widthPixels) / 1.05);

        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);

        //拍照
        takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TAkePhotos(CreatePersonActivity.this).cameraphoto(PHOTO_REQUEST_CAMERA);
                dialog.dismiss();
            }
        });
        //相册
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent localPicture = new Intent(CreatePersonActivity.this, LocalImageActivity.class);
                localPicture.putExtra("listsize", imagelistsize);
                startActivityForResult(localPicture, REQUEST_PICTURE_CODE);
                dialog.dismiss();
            }
        });
        //取消
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取图片
     *
     * @param data Intent
     */
    private void requestPicture(Intent data) {
        pathModel.remove(FRIEND_CIRCLE_ADD_PICTURE);
        if (data != null) {
            pathModel.addAll(data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS));


            imagelistsize = imagelistsize + (data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS)).size();

            //用于存放上传服务器的图片列表
            sendtoserverimagelist.addAll(data.getStringArrayListExtra(
                    LocalImageActivity.SEND_IMAGE_URIS));

        }
        if (pathModel.size() < 4) {
            pathModel.add(FRIEND_CIRCLE_ADD_PICTURE);
        }


        imagesAdapter.notifyDataSetChanged();
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void setUri(Uri uri) {
        sCurrentUri = uri;
    }

    /**
     * 选择报修时间
     */
    private void select() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select, null);
        final TextView fg1 = (TextView) view.findViewById(R.id.zb1);
        final TextView fg2 = (TextView) view.findViewById(R.id.zb2);
        final TextView fg3 = (TextView) view.findViewById(R.id.zb3);
        final TextView fg4 = (TextView) view.findViewById(R.id.zb4);
        final TextView fg5 = (TextView) view.findViewById(R.id.zb5);
        fg1.setText("时间1");
        fg2.setText("时间2");
        fg3.setText("时间3");
        fg4.setText("时间4");
        fg5.setText("时间5");

        final AlertDialog.Builder builder =
                new AlertDialog.Builder(this, android.R.style.Theme_Holo_Light_Dialog);
        dialog = builder.create();

        dialog.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.mystyle);
//        dialog.setCanceledOnTouchOutside(true);
        fg5.setAlpha(0.85f);
        fg1.setAlpha(0.85f);
        fg2.setAlpha(0.85f);
        fg3.setAlpha(0.85f);
        fg4.setAlpha(0.85f);

        dialog.show();

        DisplayMetrics dm = this.getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) ((dm.widthPixels) / 1.05);

        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);

        //
        fg5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvSelectFwsj.setText(fg5.getText().toString());
                dialog.dismiss();
            }
        });
        fg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvSelectFwsj.setText(fg1.getText().toString());
                dialog.dismiss();
            }
        });

        fg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvSelectFwsj.setText(fg2.getText().toString());
                dialog.dismiss();
            }
        });
        fg3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvSelectFwsj.setText(fg3.getText().toString());
                dialog.dismiss();
            }
        });
        fg4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvSelectFwsj.setText(fg4.getText().toString());
                dialog.dismiss();
            }
        });
    }

    private void select2() {
        if (timeList.size() > 0) {
            time = timeList.get(0).getName();
        }
        final SelectTimeAdapter adapter = new SelectTimeAdapter(this, timeList);
        adapter2 = new SelectTimeAdapter(this, timesList);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select_create2, null);
        final MyGridView gridView = (MyGridView) view.findViewById(R.id.gridview);
        final MyGridView gridView2 = (MyGridView) view.findViewById(R.id.gridview2);
        gridView.setAdapter(adapter);
        gridView2.setAdapter(adapter2);
        final AlertDialog.Builder builder =
                new AlertDialog.Builder(this, android.R.style.Theme_Holo_Light_Dialog);
        dialog = builder.create();

        dialog.getWindow().setBackgroundDrawableResource(R.drawable.transparent_bg);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setWindowAnimations(R.style.mystyle);
//        dialog.setCanceledOnTouchOutside(true);
        gridView.setAlpha(0.85f);

        dialog.show();

        DisplayMetrics dm = this.getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) ((dm.widthPixels) / 1);

        dialog.getWindow().setAttributes(lp);
        dialog.setContentView(view);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < timeList.size(); i++) {
                    timeList.get(i).isCheck = false;
                }
                timeList.get(position).isCheck = true;
                time = timeList.get(position).getName();
                adapter.notifyDataSetChanged();
                if (position == 0) {
                    flag = "";
                } else {
                    flag = "1";
                }
                getServiceTime();
            }
        });

        gridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                time = time + "  " + timesList.get(position).getName();
                mTvSelectFwsj.setText(time);
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取报修类别
     */

    private void getLevel() {
        if ("".equals(plotid))
            return;
        AjaxParams mAjaxParam = new AjaxParams();
        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        mAjaxParam.put("villageId", plotid);
        FinalHttpUtil.post(RequestMapDev.RepairManagement, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                //放置数据
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        troubleList = gson.fromJson(data, new TypeToken<PersonTrouble>() {
                        }.getType());
                        firstList.clear();
                        secondList.clear();
                        thirdList.clear();
                        if (troubleList != null && troubleList.getSubItems() != null) {
                            for (int i = 0; i < troubleList.getSubItems().size(); i++) {
                                PersonTrouble2.SubItemsEntity bean = troubleList.getSubItems().get(i);
                                if (i == 0) {
                                    firstList.add(new SelectTrouble(bean.getName(), true));
                                    leixing = firstList.get(0).getName();
                                    if (bean.getSubItems() != null) {
                                        setSecDate(bean);
                                    }
                                } else {
                                    firstList.add(new SelectTrouble(bean.getName(), false));
                                }
                                firstAdapter.notifyDataSetChanged();
                                secondAdapter.notifyDataSetChanged();
                                thirdAdapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        ToastUtil.show(CreatePersonActivity.this, msg.toString());
                    }
                } catch (Exception e) {
                    ToastUtil.show(CreatePersonActivity.this, e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                loginout_550(errorNo);
//                ToastUtil.show(CreatePersonActivity.this, strMsg);
            }
        });
    }

    public void chuli(final List<String> urls) {
        mDialogProgress.showlistviewdialog("上传图片中……");
        upLoadList.clear();
        for (int i = 0; i < urls.size(); i++) {
            String filepath = TextUtils.substring(urls.get(i), 7, urls.get(i).length());
            try {
                upLoadList.add(SaveImage.compressed(filepath));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(CreatePersonActivity.this, "图片处理错误", Toast.LENGTH_SHORT).show();
            }
        }
        for (int i = 0; i < upLoadList.size(); i++) {
            uploadImage(upLoadList.get(i));
//            uploadImage(upLoadList.get(i).substring(8,upLoadList.get(i).length()));
        }
    }

    /**
     * 上传图片
     *
     * @param path
     */
    private void uploadImage(final String path) {
        FinalHttpService.upLoadImage(path, new WithJsonListener() {
            @Override
            public void onSuccess(String code, String msg, String data) {
//                ToastUtil.show(CreatePersonActivity.this, msg);
                ToastUtil.logE("HandlePhotoActivity.this", "上传成功，结果:" + msg);
                Gson gson = new Gson();
                ArrayList<String> idList2 = new ArrayList<>();
                idList2 = (gson.fromJson(data, new TypeToken<List<String>>() {
                }.getType()));
                idList.addAll(idList2);
                if (idList.size() == upLoadList.size()) {
                    for (int i = 0; i < idList.size(); i++) {
                        if (i == idList.size() - 1) {
                            ids = ids + idList.get(i);
                        } else {
                            ids = ids + idList.get(i) + ";";
                        }

                    }
                    mDialogProgress.closedialog();
                    createOrder();
                }
            }

            @Override
            public void onError(String code, String msg) {
                ToastUtil.show(CreatePersonActivity.this, "上传失败" + msg);
                mDialogProgress.closedialog();
            }

            @Override
            public void onCookieError(String code, String msg) {
            }
        });
    }

    /**
     * 创建工单
     */

    private void createOrder() {
        AjaxParams mAjaxParam = new AjaxParams();
        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        mAjaxParam.put("repairPeople", mTvName.getText().toString().trim());
        mAjaxParam.put("phoneNumber", mTvNumber.getText().toString().trim());
        mAjaxParam.put("address", mTvPlot.getText().toString().trim());
        mAjaxParam.put("repairContent", mEvContect.getText().toString().trim());
        mAjaxParam.put("serviceTime", mTvSelectFwsj.getText().toString().trim());
        mAjaxParam.put("category", leibie);
        mAjaxParam.put("type", leixing);
        mAjaxParam.put("breakDown", guzhang);
        mAjaxParam.put("villageId", plotid);
        mAjaxParam.put("picture", ids);
        mDialogProgress.showlistviewdialog("创建工单中……");
        FinalHttpUtil.post(RequestMapDev.CreatePersonOrder, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                //放置数据
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        String id = gson.fromJson(data, String.class);
                        mDialogProgress.closedialog();
                        DialogWithDelete.showSimpleDialog(CreatePersonActivity.this, Integer.parseInt(id), 2);
//                        LoginModel loginModel = gson.fromJson(data, LoginModel.class);
//                        MyApp.instance.setToken(loginModel.getCsrfToken());//放置token值
//                        MyApp.instance.setUserType(loginModel.getRealName());//放置登录角色
//                        ToastUtil.show(CreatePublicActivity.this, "登录成功");

                    } else {
                        ToastUtil.show(CreatePersonActivity.this, msg.toString());
                    }
                } catch (Exception e) {
                    ToastUtil.show(CreatePersonActivity.this, e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                loginout_550(errorNo);
                mDialogProgress.closedialog();
//                ToastUtil.show(CreatePersonActivity.this, strMsg);
            }
        });
    }

    /**
     * 获取时间
     */
    private void getServiceDate() {
        AjaxParams mAjaxParam = new AjaxParams();
        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        FinalHttpUtil.get(RequestMapDev.getServiceDate, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                //放置数据
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        ArrayList<String> list = new ArrayList<String>();
                        list = gson.fromJson(data, new TypeToken<List<String>>() {
                        }.getType());
                        if (list.size() > 0) {
                            timeList.clear();
                            for (int i = 0; i < list.size(); i++) {
                                if (i == 0) {
                                    timeList.add(new SelectPeopleModel(list.get(i), true));
                                } else {
                                    timeList.add(new SelectPeopleModel(list.get(i), false));
                                }
                            }
                        }
                    } else {
                        ToastUtil.show(CreatePersonActivity.this, msg.toString());
                    }
                } catch (Exception e) {
                    ToastUtil.show(CreatePersonActivity.this, e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                loginout_550(errorNo);
//                ToastUtil.show(CreatePersonActivity.this, strMsg);
            }
        });
    }

    /**
     * 获取时间段
     */
    private void getServiceTime() {
        AjaxParams mAjaxParam = new AjaxParams();
        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        mAjaxParam.put("flag", flag);
        FinalHttpUtil.get(RequestMapDev.getServiceTime, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                //放置数据
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        ArrayList<String> list = new ArrayList<String>();
                        list = gson.fromJson(data, new TypeToken<List<String>>() {
                        }.getType());
                        if (list.size() > 0) {
                            timesList.clear();
                            for (int i = 0; i < list.size(); i++) {
                                timesList.add(new SelectPeopleModel(list.get(i), false));
                            }
                            adapter2.notifyDataSetChanged();
                        }
                    } else {
                        ToastUtil.show(CreatePersonActivity.this, msg.toString());
                    }
                } catch (Exception e) {
//                    ToastUtil.show(CreatePersonActivity.this, e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                loginout_550(errorNo);
//                ToastUtil.show(CreatePersonActivity.this, strMsg);
            }
        });
    }

    private void setSecDate(PersonTrouble2.SubItemsEntity bean) {
        if (bean.getSubItems() != null) {
            for (int j = 0; j < bean.getSubItems().size(); j++) {
                PersonTrouble3.SubItemsEntity beanu = bean.getSubItems().get(j);
                if (j == 0) {
                    secondSelected = 0;
                    secondList.add(new SelectTrouble(beanu.getName(), true));
                    leibie = secondList.get(0).getName();
                    setThirdData(beanu);
                } else {
                    secondList.add(new SelectTrouble(beanu.getName(), false));
                }
            }
        }
    }

    private void setThirdData(PersonTrouble3.SubItemsEntity beanu) {
        if (beanu.getSubItems() != null) {
            for (int z = 0; z < beanu.getSubItems().size(); z++) {
                PersonTrouble4.SubItemsEntity bbean = beanu.getSubItems().get(z);
                if (z == 0) {
                    thirdSelected = 0;
                    thirdList.add(new SelectTrouble(bbean.getName(), true));
                    guzhang = thirdList.get(0).getName();
                } else {
                    thirdList.add(new SelectTrouble(bbean.getName(), false));
                }
            }
        }
    }
}
